package com.emm.yixun.mobile.fragment;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.emm.yixun.mobile.R;
import com.emm.yixun.mobile.application.EmmApplication;
import com.emm.yixun.mobile.model.GetMemberInfo;
import com.emm.yixun.mobile.model.GetMemberScoreList;
import com.emm.yixun.mobile.ui.personal.ArmoryActivity;
import com.emm.yixun.mobile.ui.personal.PersonalDateActivity;
import com.eroad.product.tools.PickerView;
import com.eroad.product.tools.PickerView.onSelectListener;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import xf.tools.Loading;
import xf.tools.RoundImageView;

/**
 * 我的
 */
public class MyDataFragment extends Fragment {

    private static final String TAG = "MyDataFragment";

    FragmentActivity root = null;

    /**
     * 英雄榜、排行榜
     */
    RelativeLayout gotoArmory;

    /**
     * 账号设置
     */
    RelativeLayout personal_mydate;

    /**
     * 标题
     */
    TextView title_main;

    /**
     * 业绩模块
     */
    LinearLayout count_layout;

    /**
     * 时间
     */
    TextView name_time;

    /**
     * 时间类型 默认今天
     */
    String timeType = "1";

    /**
     * 筛选条件
     */
    LinearLayout open_layout;

    /* ---公用选择框--- */
    View view;
    PopupWindow popu;

    /**
     * 选中内容
     */
    String selectName;

    /**
     * 选中下标
     */
    int SelectID;

    /**
     * 选项数据
     */
    ArrayList<String> listname;
    /* ---公用选择框--- */

    /**
     * 认筹数量
     */
    TextView count_1;

    /**
     * 认购数量
     */
    TextView count_2;

    /**
     * 签约数量
     */
    TextView count_3;

    /**
     * 个人成绩
     */
    GetMemberScoreList getScore;

    /**
     * 个人信息
     */
    GetMemberInfo getinfo;

    /**
     * 头像
     */
    RoundImageView rdimageview_mydate;

    /**
     * 用户名
     */
    TextView user_name;

    /**
     * 电话号码
     */
    TextView user_phone;

    /**
     * 认筹认购签约金额
     */
    TextView price_1, price_2, price_3;

    /**
     * 团队排名
     */
    RelativeLayout gotoArmory_2;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragmentd, null);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        root = getActivity();
        title_main = (TextView) root.findViewById(R.id.mydate_include).findViewById(R.id.title_main);
        title_main.setText(getString(R.string.my));
        count_layout = (LinearLayout) root.findViewById(R.id.count_layout);
        open_layout = (LinearLayout) root.findViewById(R.id.open_layout);
        name_time = (TextView) root.findViewById(R.id.name_time);
        name_time.setText("今天");
        count_1 = (TextView) root.findViewById(R.id.count_1);
        count_2 = (TextView) root.findViewById(R.id.count_2);
        count_3 = (TextView) root.findViewById(R.id.count_3);
        rdimageview_mydate = (RoundImageView) root.findViewById(R.id.rdimageview_mydate);
        user_name = (TextView) root.findViewById(R.id.user_name_mydate);
        user_phone = (TextView) root.findViewById(R.id.user_phone);
        price_1 = (TextView) root.findViewById(R.id.price_1);
        price_2 = (TextView) root.findViewById(R.id.price_2);
        price_3 = (TextView) root.findViewById(R.id.price_3);
        gotoArmory_2 = (RelativeLayout) root.findViewById(R.id.gotoArmory_2);

        initView();
        initBtn();

        Log.v(TAG, "isGradesMine :" + EmmApplication.getData(EmmApplication.isGradesMine));
        // 我的菜单权限下按钮权限：我的成绩 String(1) 我的成绩：0 无 1 有
        if ("1".equals(EmmApplication.getData(EmmApplication.isGradesMine))) {
            count_layout.setVisibility(View.VISIBLE);
            open_layout.setVisibility(View.VISIBLE);
        } else {
            count_layout.setVisibility(View.GONE);
            open_layout.setVisibility(View.GONE);
        }
        Log.v(TAG, "isHeroListMine :" + EmmApplication.getData(EmmApplication.isHeroListMine));
        // 我的菜单权限下按钮权限：个人英雄榜 String(1) 个人英雄榜：0 无 1 有
        if ("1".equals(EmmApplication.getData(EmmApplication.isHeroListMine))) {
            gotoArmory.setVisibility(View.VISIBLE);
        } else {
            gotoArmory.setVisibility(View.GONE);
        }

        Log.v(TAG, "isTeamRankingMine :" + EmmApplication.getData(EmmApplication.isTeamRankingMine));
        // 我的菜单权限下按钮权限：团队排名 String(1) 团队排名：0 无 1 有
        if ("1".equals(EmmApplication.getData(EmmApplication.isTeamRankingMine))) {
            gotoArmory_2.setVisibility(View.VISIBLE);
        } else {
            gotoArmory_2.setVisibility(View.GONE);
        }
    }

    /**
     * <p>
     * <b>Title：</b> 初始化view
     * </p>
     * <p>
     * <b>Description：</b>
     * </p>
     *
     * @author tangxin
     * @date 2016年12月9日 下午6:06:43
     */
    private void initView() {
        gotoArmory = (RelativeLayout) root.findViewById(R.id.gotoArmory);
        personal_mydate = (RelativeLayout) root.findViewById(R.id.personal_mydate);
    }

    /**
     * <p>
     * <b>Title：</b> 初始化监听事件
     * </p>
     * <p>
     * <b>Description：</b>
     * </p>
     *
     * @author tangxin
     * @date 2016年12月7日 上午10:36:44
     */
    private void initBtn() {

        // 英雄榜、排行榜
        gotoArmory.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!EmmApplication.isErrorCode()) {
                    EmmApplication.T();
                    return;
                }
                h.sendEmptyMessage(1);
                startActivity(new Intent(root, ArmoryActivity.class));
            }
        });

        // 账号设置
        personal_mydate.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                // 账号设置
                startActivity(new Intent(root, PersonalDateActivity.class));
            }
        });

        // 筛选条件
        open_layout.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                listname = new ArrayList<String>();
                listname.add("今天");
                listname.add("昨天");
                listname.add("本周");
                listname.add("上周");
                listname.add("本月");
                listname.add("上月");
                listname.add("近三月");
                listname.add("今年");
                SetzpPopu(listname, "时间选择", name_time);
            }
        });

        // 团队排名
        gotoArmory_2.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(root, ArmoryActivity.class);
                intent.putExtra("position", 2);
                startActivity(intent);
            }
        });

    }

    @SuppressLint("HandlerLeak")
    Handler h = new Handler() {
        public void handleMessage(android.os.Message msg) {
            if (msg.what == 1) {
                Loading.showDialogForLoading(root, "加载中...", false, true, 10000);
            } else if (msg.what == 2) {
                Loading.hideDialogForLoading();
            }
        }
    };

    /**
     * <p>
     * <b>Title：</b> 选项框
     * </p>
     * <p>
     * <b>Description：</b>
     * </p>
     *
     * @param listname 选项内容list
     * @param title    选项名
     * @param ed       选择结果显示的edittext
     * @author tangxin
     * @date 2016年12月6日 下午5:44:05
     */
    public void SetzpPopu(final List<String> listname, String title, final TextView ed) {
        view = LayoutInflater.from(root).inflate(R.layout.popu_zp, null);
        popu = new PopupWindow(view, android.support.v4.view.ViewPager.LayoutParams.FILL_PARENT,
                android.support.v4.view.ViewPager.LayoutParams.FILL_PARENT);
        popu.setFocusable(true);
        popu.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        popu.showAtLocation(view, Gravity.BOTTOM, 0, 0);
        popu.showAsDropDown(view, 0, 0);
        popu.setFocusable(true);
        popu.setOutsideTouchable(true);
        view.setFocusable(true);
        view.setFocusableInTouchMode(true);
        view.setOnKeyListener(new OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_BACK) {
                    popu.dismiss();
                    EmmApplication.setLog(root);
                }
                return false;
            }
        });
        view.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                popu.dismiss();
                EmmApplication.setLog(root);
            }
        });

        PickerView select_pick = (PickerView) view.findViewById(R.id.select_pick);
        TextView shuerbtn = (TextView) view.findViewById(R.id.shuerbtn);
        RelativeLayout relative_all = (RelativeLayout) view.findViewById(R.id.relative_all);
        ImageView dis_btn = (ImageView) view.findViewById(R.id.dis_btn);

        selectName = listname.get(0);

        // 取消
        dis_btn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                popu.dismiss();
                EmmApplication.setLog(root);
            }
        });
        TextView title_select = (TextView) view.findViewById(R.id.title_select);
        title_select.setText(title);

        // 设置数据到滑动控件
        select_pick.setData(listname);
        // 滑动监听
        select_pick.setOnSelectListener(new onSelectListener() {
            @Override
            public void onSelect(String text, int id) {
                // 选中的
                selectName = text;
                SelectID = id;
            }
        });

        // 默认选中的
        select_pick.setSelected(0);
        shuerbtn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                // 确定
                popu.dismiss();
                EmmApplication.setLog(root);
                ed.setText(selectName);

                // 获取筛选条件值对应的类型标识
                if ("今天".equals(selectName)) {
                    timeType = "1";
                } else if ("昨天".equals(selectName)) {
                    timeType = "2";
                } else if ("本周".equals(selectName)) {
                    timeType = "3";
                } else if ("上周".equals(selectName)) {
                    timeType = "4";
                } else if ("本月".equals(selectName)) {
                    timeType = "5";
                } else if ("上月".equals(selectName)) {
                    timeType = "6";
                } else if ("近三月".equals(selectName)) {
                    timeType = "7";
                } else if ("今年".equals(selectName)) {
                    timeType = "8";
                }

                // 调用接口
                getMemberScoreList(timeType);
            }
        });

        relative_all.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                // 点击事件消耗
            }
        });
    }

    @Override
    public void onResume() {

        getMemberInfo();// 查询个人信息
        getMemberScoreList(timeType);// 查询成绩
        Log.v(TAG, "---.>onResume");
        super.onResume();
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        if (hidden) {
            Log.v(TAG, "1");
        } else {
            Log.v(TAG, "2");
            Reload();
        }
    }

    /**
     * <p>
     * <b>Title：</b> 刷新数据
     * </p>
     * <p>
     * <b>Description：</b>
     * </p>
     *
     * @author tangxin
     * @date 2016年12月7日 上午10:38:29
     */
    public void Reload() {
        getMemberScoreList(timeType);
        getMemberInfo();
    }

    /**
     * <p>
     * <b>Title：</b> 个人成绩查询接口
     * </p>
     * <p>
     * <b>Description：</b>
     * </p>
     *
     * @param timeType
     * @author tangxin
     * @date 2016年12月7日 上午10:38:44
     */
    private void getMemberScoreList(String timeType) {
        Log.v(TAG, "timeType-->" + timeType);
        if (!EmmApplication.isErrorCode()) {
            return;
        }
        EmmApplication.updateUrl("getMemberScoreList");
        Map<String, String> map = new HashMap<String, String>();
        map.put("version", EmmApplication.getPackageManager(5));
        map.put("merchantId", EmmApplication.getData(EmmApplication.merchantId));
        map.put("token", EmmApplication.getToken());
        map.put("userId", EmmApplication.getUserId());
        map.put("timeType", timeType);
        map.put("projectCode", EmmApplication.getProjectCode());
        map.put("terminalCode", EmmApplication.getPackageManager(2));
        map.put("scoreCategory", "1");
        Map<String, Object> paramsMap = new HashMap<String, Object>();
        paramsMap.put("params", map);
        JSONObject json = new JSONObject(paramsMap);
        String jsonstr = json.toString();
        RequestParams params = new RequestParams();
        params.put("body", jsonstr);
        Log.v(TAG, "getMemberScoreList-->post:" + EmmApplication.urlStr + "?body=" + jsonstr);
        AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
        asyncHttpClient.post(EmmApplication.urlStr, params, new AsyncHttpResponseHandler() {
            @Override
            public void onFailure(Throwable error, String content) {
                super.onFailure(error, content);
                Loading.hideDialogForLoading();
                Log.v(TAG, "请求结束error:" + error + "==" + content);
            }

            @Override
            public void onFinish() {
                Loading.hideDialogForLoading();
                Log.v(TAG, "请求结束");
                super.onFinish();
            }

            @Override
            public void onStart() {
                super.onStart();
                Loading.showDialogForLoading(root, "正在加载...", false, true, 60000);
                Log.v(TAG, "请求开始");
            }

            @Override
            public void onSuccess(String content) {
                super.onSuccess(content);
                if (content == null) {
                    return;
                }
                Log.v("content", content);
                JSONObject jsonObj = JSONObject.parseObject(content);
                JSONObject resData = (JSONObject) jsonObj.get("resData");
                if (resData == null) {
                    Log.v(TAG, "信息返回值为空");
                    return;
                }

                getScore = JSONObject.parseObject(resData.toString(), GetMemberScoreList.class);

                if ("1".equals(getScore.getResult())) {
                    Log.v("获取成功", "");

                    count_1.setText(EmmApplication.isNull(getScore.getRcScoreNum()) ? getScore.getRcScoreNum() : "0");// 认筹

                    count_2.setText(EmmApplication.isNull(getScore.getRgScoreNum()) ? getScore.getRgScoreNum() : "0");// 认购

                    count_3.setText(EmmApplication.isNull(getScore.getQyScoreNum()) ? getScore.getQyScoreNum() : "0");// 签约

                    price_1.setText(EmmApplication.isNull(getScore.getSubscribeAmount()) ? getScore.getSubscribeAmount()
                            : "0");// 认购金额
                    price_2.setText(EmmApplication.isNull(getScore.getSignedAmount()) ? getScore.getSignedAmount() : "0");// 签约
                    price_3.setText(!EmmApplication.isNull(getScore.getReturnAmount()) ? "0" : getScore
                            .getReturnAmount());// 回款

                } else {
                    EmmApplication.T(getScore.getErrorMsg().toString());
                    Log.v("获取失败", "errorCode:" + getScore.getErrorCode().toString() + "errorMsg:"
                            + getScore.getErrorMsg().toString());
                }
            }
        });
    }

    /**
     * <p>
     * <b>Title：</b> 个人信息查询接口
     * </p>
     * <p>
     * <b>Description：</b>
     * </p>
     *
     * @author tangxin
     * @date 2016年12月7日 上午10:39:08
     */
    private void getMemberInfo() {
        EmmApplication.updateUrl("getMemberInfo");
        Map<String, String> map = new HashMap<String, String>();
        map.put("version", EmmApplication.getPackageManager(5));
        map.put("merchantId", EmmApplication.getData(EmmApplication.merchantId));
        map.put("token", EmmApplication.getToken());
        map.put("userId", EmmApplication.getUserId());
        map.put("terminalCode", EmmApplication.getPackageManager(2));
        Map<String, Object> paramsMap = new HashMap<String, Object>();
        paramsMap.put("params", map);
        JSONObject json = new JSONObject(paramsMap);
        String jsonstr = json.toString();
        RequestParams params = new RequestParams();
        params.put("body", jsonstr);
        Log.v("getMemberInfo-->post", EmmApplication.urlStr + "?body=" + jsonstr);
        AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
        asyncHttpClient.post(EmmApplication.urlStr, params, new AsyncHttpResponseHandler() {
            @Override
            public void onFailure(Throwable error, String content) {
                super.onFailure(error, content);
                Loading.hideDialogForLoading();
                Log.v(TAG, "请求结束error:" + error + "==" + content);
            }

            @Override
            public void onFinish() {
                Loading.hideDialogForLoading();
                Log.v(TAG, "请求结束");
                super.onFinish();
            }

            @Override
            public void onStart() {
                super.onStart();
                Loading.hideDialogForLoading();
                Loading.showDialogForLoading(root, "正在加载...", false, true, 60000);
                Log.v(TAG, "请求开始");
            }

            @Override
            public void onSuccess(String content) {
                super.onSuccess(content);
                if (content == null) {
                    return;
                }
                Log.v("content", "content=>" + content);
                JSONObject jsonObj = JSONObject.parseObject(content);
                JSONObject resData = (JSONObject) jsonObj.get("resData");
                if (resData == null) {
                    Log.v(TAG, "信息返回值为空");
                    return;
                }

                getinfo = JSONObject.parseObject(resData.toString(), GetMemberInfo.class);

                if ("1".equals(getinfo.getResult())) {
                    Log.v("获取成功", "");
                    // 渲染几面
                    user_name.setText(getinfo.getName());// 名称
                    user_phone.setText(getinfo.getMobile());// 电话
                    EmmApplication.image(R.drawable.touxiang);// 头像
                    EmmApplication.imageLoader.displayImage(getinfo.getHeadPic(), rdimageview_mydate, EmmApplication.options);
                } else {
                    EmmApplication.T(getinfo.getErrorMsg().toString());
                    Log.v("获取失败", "errorCode:" + getinfo.getErrorCode().toString() + "errorMsg:"
                            + getinfo.getErrorMsg().toString());
                }
            }
        });
    }

}
